package com.example.controller;

import com.example.entity.Branches;
import com.example.service.BranchesService;
import com.example.service.CityAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BranchesController {

    @Autowired
    CityAreaService cityAreaService;

    @Autowired
    BranchesService branchesService;

    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("brancheslist",branchesService.getAll());
        return mv;
    }

    @GetMapping("/add")
    public ModelAndView addpre(){
        ModelAndView mv = new ModelAndView("edit");
        mv.addObject("areas",cityAreaService.getAll());
        mv.addObject("action","add");
        return mv;
    }

    @PostMapping("/add")
    public String addsave(Branches branches){
        this.branchesService.add(branches);
        return "redirect:index";
    }

    @GetMapping("/delete")
    public String delete(int id){
        this.branchesService.delete(id);
        return "redirect:index";
    }

    @GetMapping("/update")
    public ModelAndView updatepre(int id){
        ModelAndView mv = new ModelAndView("edit");
        mv.addObject("branches",branchesService.getOne(id));
        mv.addObject("areas",cityAreaService.getAll());
        mv.addObject("action","update");
        return mv;
    }

    @PostMapping("/update")
    public String updatesave(Branches branches){
        this.branchesService.update(branches);
        return "redirect:index";
    }
}
